//
// Created by lwj66 on 24-6-6.
//

#include "seqlist.h"

void slInit(SL* ps)
{
    slType* n = (slType*) malloc(INIT_CAPACITY * sizeof (slType));
    if(n == NULL)
    {
        perror("分配内存失败\n");
        exit(1);
    }
    ps -> sl = n;
    ps -> capacity = INIT_CAPACITY;
    ps -> size = 0;
}

void slGrow(SL* ps)
{
    assert(ps);
    if(ps->capacity != ps->size)
        return;
    int newCapacity = ps->capacity == 0 ? INIT_CAPACITY : ps->capacity * 2;
    slType* n = (slType*) realloc(ps->sl, newCapacity * sizeof (slType));
    if(n == NULL)
    {
        perror("内存重新分配失败\n");
        exit(1);
    }
    ps->sl = n;
    ps->capacity = newCapacity;
}

void slPushFront(SL* ps, slType value)
{
    assert(ps);
    slGrow(ps);
    int i;
    for(i = ps->size - 1; i >= 0; i--)
        ps->sl[i + 1] = ps->sl[i];
    ps->sl[0] = value;
    ps->size++;
}

void slPopFront(SL* ps)
{
    assert(ps);
    int i = 1;
    for (; i < ps->size; i++)
        ps->sl[i - 1] = ps->sl[i];
    ps->size--;
}

void slPushBack(SL* ps, slType value)
{
    assert(ps);
    slGrow(ps);
    ps->sl[ps->size] = value;
    ps->size++;
}

void slPopBack(SL*ps)
{
    assert(ps);
    ps->size--;
}

void slInsertAT(SL* ps, slType value, size_t index)
{
    assert(ps);
    assert(index >= 0 && index <= ps->size);
    size_t i;
    for (i = ps->size - 1; i >= index; i--)
        ps->sl[i + 1] = ps->sl[i];
    ps->sl[index] = value;
    ps->size++;
}

void slRemoveAT(SL* ps, size_t index)
{
    assert(ps);
    assert(index >= 0 && index < ps->size);
    size_t i;
    for(i = index; i < ps->size - 1; i++)
        ps->sl[i] = ps->sl[i + 1];
    ps->size--;
}

void Printf(SL* ps)
{
    assert(ps);
    for (int i = 0; i < ps->size; ++i)
        printf(TYPESPECIFIER, ps->sl[i]);
    printf("\n");
}

void slClear(SL* ps)
{
    assert(ps);
    free(ps->sl);
    ps->sl = NULL;
    ps->size = 0;
    ps->capacity = 0;
    ps = NULL;
}
